<template>
  <div class="play-bar" :style="{'bottom': 0}">
    <div class="content posi-rel">
      <!-- 上一首、播放/暂停、下一首 -->
      <div class="icon-play H100pc disinblock clearfix mr20">
          <a href="javascript:;" class="fl prev cursor-pointer" title="上一首" @click='playLastSong()'></a>
          <a href="javascript:;" reg="play" 
            :class="['fl','play', 'cursor-pointer', {'pasue':isPlayFlag}]"
            title="播放/暂停" @click="playOrPasMusic()"></a>
          <a href="javascript:;" class="fl next cursor-pointer" title="下一首" @click="playNextSong()"></a>
      </div>
      <!-- 歌曲进度条 -->
      <audio ref="audio" :src=songUrl type="audio/ogg"></audio>
      <div class="control disinblock H100pc clearfix">
        <!-- 歌曲封面 -->
        <div class="c-cover fl mr10">
          <a href="javascript:;">
            <el-image :src=this.coverUrl class="cover-img"></el-image>
          </a>
        </div>
        <div class="c-bar fl mr10 ml10">
          <div class="title fs12">
            <a href="javascript:;" class="song-name mr10 fcWhite" :title=this.songName>{{ this.songName }}</a>
            <a href="javascript:;" class="auther mr10 fcLightgray" :title=this.songAuthor>{{ this.songAuthor }}</a>
            <a href="javascript:;" class="link" title="来自歌单"></a>
          </div>
          <div class="posi-rel">
            <el-slider v-model="curTimeWidth" :max="100" @change="dragFunc">
            </el-slider>
          </div>
        </div>
        <!-- 时间 -->
        <div class="time fl fcWhite fs12 ml20">
          <span class="curTime">{{ this.currentTime }}</span> / 
          <span class="duration">{{ this.duration }}</span>
        </div>
      </div>
      <!-- 歌曲操作按钮 -->
      <div class="opt-panel H100pc disinblock clearfix">
        <div class="fl panel-l">
          <a href="javascript:;" class="opt-icon lyric mr10 disinblock" title="画中画歌词"
            @click='isLyricShow = !isLyricShow'></a>
          <a href="javascript:;" class="opt-icon collect mr10 disinblock" title="收藏"></a>
          <a href="javascript:;" class="opt-icon share mr10 disinblock" title="分享"></a>
        </div>
        <div class="fl panel-r">
          <a href="javascript:;" class="opt-icon volume mr10 disinblock" title="音量"></a>
          <a href="javascript:;" class="opt-icon cycle mr10 disinblock" title="循环"></a>
          <a href="javascript:;" class="opt-icon playlist mr10 disinblock cursor-pointer" title="播放列表" @click="openPlayRecord()">
            <span class='fcWhite fr mr20 fs12 mt5'>{{ playRecordList.length }}</span>
          </a>
        </div>
      </div>
    </div>
    <div class="play-record posi-ab" v-show="isOpenPlayRecord">
      <play-record @initAudio=initAudio :playRecordData=playRecordList
        @setPlayRecord=setPlayRecord @playOrPasMusic=playOrPasMusic
        @getLyric=getLyric :listUpdated=listUpdated></play-record>
    </div>
    <Lyric class="posi-ab" :lyric=lyric v-show="isLyricShow" @updateLyric=updateLyric
      :songName=songName :songAuthor=songAuthor :currentTime=currentTime :lyricIndex=lyricIndex></Lyric>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import PlayRecord from './playRecord.vue'
import Lyric from './lyric.vue'
export default {
  name: 'playBar',
  data() {
    return {
      bottom: "0px",
      currentTime: '00:00',
      duration: '00:00',
      isPlayFlag: false,
      coverUrl: '',
      songName: '',
      songAuthor: '',
      songUrl: '',
      curTimeWidth: 0, // 播放条百分比
      durationNum: 0,
      isOpenPlayRecord: false, // 是否打开播放列表
      playRecordList: [],
      lyric: [],
      isLyricShow: false,
      lyricArr: [],
      lyricIndex: 0,
      listUpdated: 1,
      musicIndex: 0,
      manualChangeIndexFlag: false // 是否手动切换上一首下一首
    }
  },
  mounted() {
    document.addEventListener("mousemove", e => {
      this.touchmove(e)
    });
    // this.getPlayRecord()
  },
  methods: {
    touchmove(e) {
      let height = document.documentElement.clientHeight || document.body.clientHeight;
        if (e.y >= height - 50) {
          this.bottom = "0"
        } else {
          this.timer = setTimeout(() => {
            this.bottom = "-48px"
          }, 4000)
        }
    },
    initAudio(pauseFlag, curSongInfo) {
      console.log('init audio!')
      this.lyricIndex = 0
      this.updateData(curSongInfo)
      !curSongInfo && this.setPlayRecord()
      const self = this
      const audio = this.$refs.audio
      audio.load() // 解决动态绑定音频src时，duration为 NaN的问题
      audio.play()
      audio.oncanplay = () => { // 在加载完资源后，可以播放的回调函数里，再调用 play()方法
        audio.play()
        self.getLyric(self.songid)
        self.duration = self.secondsFormat2(parseInt(audio.duration))
        audio.addEventListener('timeupdate', () => {
          if (!isNaN(audio.duration)) {
            self.duration = self.secondsFormat2(parseInt(audio.duration))
            self.durationNum = parseInt(audio.duration)
            self.currentTime = self.secondsFormat2(parseInt(audio.currentTime))
            self.curTimeWidth = parseInt(audio.currentTime / audio.duration * 100); // 用时间比来获取进度条的值
            if (pauseFlag && self.isPlayFlag == false) {
              audio.pause()
            }
            if (self.lyricArr.length > 1) {
              self.lyricArr.forEach((item, i) => { // 歌词与进度同步
                if (self.currentTime == item.time) {
                  self.lyricIndex = i
                }
              })
            }
          }
        },false);

        audio.addEventListener('ended', () => {
            self.curTimeWidth = 0; // 当播放完成，进度条跳到开始
            self.currentTime = "00:00"
            self.isPlayFlag = false
        })
      }
    },
    updateData(recordList) {
      this.curTimeWidth = 0
      if (recordList) {
        this.coverUrl = recordList.al.picUrl
        this.songAuthor = recordList.author
        this.songName = recordList.name
        this.songUrl = recordList.songUrl
      } else {
        let { songs: [{ al, ar }] } = this.songinfo
        this.songUrl = this.songinfo.songurl.url
        this.songName = this.songinfo.songs[0].name
        this.coverUrl = al.picUrl
        this.songAuthor = []
        ar.forEach(item => {
          this.songAuthor.push(item.name)
        })
        this.songAuthor = this.songAuthor.join("/")
      }
    },
    // 秒 转换为 分秒
    secondsFormat2(s) {
      let minute = Math.floor(s / 60);
      let second = s - minute * 60;
      return  minute.toString().padStart(2, '0') + ":" + second.toString().padStart(2, '0');
    },
    playOrPasMusic(flag) {
      if (typeof flag !== "undefined") {
        this.isPlayFlag = flag
      } else {
        this.isPlayFlag = !this.isPlayFlag
      }
    },
    dragFunc() {
      const audio = this.$refs.audio
      audio.currentTime = audio.duration / 100 * this.curTimeWidth 
    },
    openPlayRecord() {
      this.isOpenPlayRecord = !this.isOpenPlayRecord
    },
    setPlayRecord(list) {
      let self = this
      if (list) {
        this.playRecordList = list
      } else {
        let repeatFlag = false
        this.playRecordList.forEach((item, i) => {
          item.active = false
          item.index = i
          if (item.name == self.songName) {
            repeatFlag = true
            item.active = true
            this.musicIndex = i
            this.manualChangeIndexFlag = false
          }
        })
        // 播放新音乐
        if (!repeatFlag) {
          this.playRecordList.push({
            ...this.songinfo.songs[0],
            songUrl: this.songinfo.songurl.url,
            active: true,
            index: this.playRecordList.length
          })
          this.musicIndex = this.playRecordList.length
          this.manualChangeIndexFlag = false
        }
      }
      this.listUpdated += 1
      localStorage.setItem("playRecord", JSON.stringify(this.playRecordList))
    },
    async getLyric(id) {
      const param = { id }
      try {
        let res = await this.$api.getLyric(param)
        this.lyric = res.data.lrc.lyric
      } catch(err) {
        console.log('nolyric', err)
        this.lyric = '无歌词'
      }
    },
    updateLyric(arr) {
      this.lyricArr = arr
    },
    playLastSong() {
      this.manualChangeIndexFlag = true
      this.musicIndex--
    }
  },
  watch: {
    isPlayFlag() {
      const audio = this.$refs.audio
      if (!this.isPlayFlag) {
        audio.pause()
      } else {
        audio.play()
      }
    },
    songid() {
      if (this.songinfo.checkmusic == "ok") { // 如果音乐可用，再播放
        this.bottom = "0"
        this.playOrPasMusic(true)
        this.initAudio()
      }
    },
    musicIndex() {
      if (this.manualChangeIndexFlag) {
        let curSongList = this.playRecordList[this.musicIndex]
        this.initAudio(false, curSongList)
      }
    }
  },
  computed: {
     ...mapGetters([
      'songinfo',
      'songid',
    ])
  },
  components: {
    PlayRecord,
    Lyric
  }
}
</script>

<style lang="less">
  .play-bar {
    position: fixed;
    bottom: -48px;
    z-index: 10000;
    width: 100%;
    height: 60px;
    background-color: rgba(0, 0, 0, 0.8);
    box-shadow: 0px -2px 5px #000;
    transition: all ease 0.7s;
    .content {
      width: 1100px;
      height: 100%;
      margin: 0 auto;
      .icon-play {
        width: 130px;
        .prev, .next, .play {
          background: url("../../assets/playbar.png");
        }
        .prev, .next {
          width: 25px;
          height: 25px;
        }
        .prev {
          background-position: -1px -131px;
          margin-top: 15px;
          margin-left: 17px;
          &:hover {
            background-position: -31px -131px;
          }
        }
        .play, .pasue {
          width: 35px;
          height: 35px;
          background-position: 0px -205px;
          margin-top: 11px;
          margin-left: 10px;
          &:hover {
            background-position: -40px -205px;
          }
        }
        .play.pasue {
          background-position: 0px -166px;
          &:hover {
            background-position: -40px -166px;
          }
        }
        .next {
          background-position: -82px -131px;
          margin-top: 15px;
          margin-left: 10px;
          &:hover {
            background-position: -112px -131px;
          }
        }
      }
      .control {
        width: 680px;
        padding-top: 5px;
        height: calc(100% - 5px);
        .c-cover {
          width: 34px;
          height: 34px;
          background-color: green;
          margin-top: 9px;
          .cover-img {
            width: 100%;
            height: 100%;
          }
        }
        .c-bar {
          height: 100%;
          /deep/ .el-slider__runway {
            width: 485px;
          }
        }
        .time {
          margin-top: 25px;
        }
      }
      .opt-panel {
        .opt-icon {
          width: 25px;
          height: 25px;
          background-color: blue;
          background: url("../../assets/playbar.png");
        }
        .panel-l, .panel-r {
          margin-top: 17px;
          margin-left: 10px;
          height: 25px;
        }
        .panel-l {
          border-right: 1px solid #312d2d;
          .lyric {
            background: url("../../assets/lyricIcon.png");
            background-position: 0 0;
            &:hover { 
              background-position: 0px -25px;
            }
          }
          .collect {
            background-position: -88px -163px;
            &:hover { 
              background-position: -88px -189px;
            }
          }
          .share {
            background-position: -113px -163px;
            &:hover { 
              background-position: -113px -189px;
            }
          }
        }
        .panel-r {
          .volume {
            background-position: 0px -247px;
            &:hover { 
              background-position: -29px -247px;
            }
          }
          .cycle {
            background-position: -4px -343px;
            &:hover { 
              background-position: -34px -343px;
            }
          }
          .playlist {
            width: 60px;
            background-position: -46px -69px;
            &:hover { 
              background-position: -46px -99px;
            }
            .record-num {
              margin-top: 5px;
            }
          }
        }
      }
    }
    .play-record {
      bottom: 62px;
      right: 165px;
      width: 500px;
      height: 300px;
      background-color: #121212;
    }
  }
</style>
